export default {
  install: function (Vue) {
    /**  create by  heyuqiu  2020-4-10  **/
    // 获取存储在sessionStorage中的用户信息
    Vue.prototype.getUserInfo = () => {
      let userInfo = sessionStorage.getItem('userInfo');
      if (userInfo == null) return userInfo;
      else return JSON.parse(userInfo);
    };

    // 重设表头   （后台返回表头，重设校验规则）
    Vue.prototype.getRuleHeader = (arr) => {
      return arr.map(el => {
        let obj = JSON.parse(JSON.stringify(el));
        let rules = [];
        if (obj.rule) {
          if (obj.rule['required']) {
            let rule = {required: true, message: '此项为必填项！'};
            rules.push(rule)
          }
          if (obj.rule['reg']) {
            try {
              let reg = obj.rule['reg'].replace(/\\/g, "\\\\");
              let pattern = new RegExp(reg);
              let rule = {pattern, message: obj.rule['desc'] || `请输入正确格式！`};
              rules.push(rule)
            } catch (err) {
              console.log(err)
            }
          }
          if ((obj.type === 'text' || obj.type === 'textarea' || obj.type === 'password' || obj.type === 'autocomplete') && (obj.rule['max'] || obj.rule['min'])) {
            let rule;
            if (obj.rule['max'] && obj.rule['min']) {
              rule = {
                min: obj.rule['min'],
                max: obj.rule['max'],
                message: `长度在 ${obj.rule['min']} 到 ${obj.rule['max']} 个字符`,
                trigger: 'blur'
              }
            } else if (obj.rule['max']) {
              rule = {max: obj.rule['max'], message: `长度不能超过 ${obj.rule['max']} 个字符`, trigger: 'blur'}
            } else {
              rule = {min: obj.rule['min'], message: `长度不能少于 ${obj.rule['min']} 个字符`, trigger: 'blur'}
            }
            rules.push(rule)
          } else if (obj.type === 'number') {
            rules.push({type: 'number', message: '请输入正确数据', trigger: 'blur', transform: (value) => Number(value)});
            if (obj.rule['highVal'] && obj.rule['highVal'] >= 0) {
              obj.max = obj['containsHigh'] ? obj.rule['highVal'] : obj.rule['highVal'] - 1;
            } else if (obj.rule['lowVal'] && obj.rule['lowVal'] >= 0) {
              obj.min = obj['containsLow'] ? obj.rule['lowVal'] : obj.rule['lowVal'] + 1;
            }
          }
          if (obj.type === 'text') {
            if (obj.header.indexOf('邮箱') !== -1) {
              rules.push({type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']})
            } else if (obj.header.indexOf('手机号') !== -1) {
              rules.push({pattern: /^1[3-9](\d{9})$/, message: '请输入正确的手机号', trigger: 'change'},
                {max: 11, message: '请输入11位手机号', trigger: 'change'})
            }
          }
        }
        obj.rule = rules;
        return obj;
      })
    };
    // 重设表头 （类型匹配正则）  ruleObj类型：{field1: 'number', field2: 'email', ...}
    Vue.prototype.getPatternHeader = (header, ruleObj) => {
      return header.map(el => {
        let obj = JSON.parse(JSON.stringify(el));
        let rules = [];
        if(obj.rule) {
          if(obj.rule instanceof Array) {
            rules = obj.rule;
          } else {
            rules.push(obj.rule);
          }
        }
        if (ruleObj instanceof Object && Object.keys(ruleObj).length > 0) {
          let types = ['string', 'number', "boolean", 'method', 'regexp', 'integer', 'float', 'array', 'object', 'enum', 'date', 'url', 'hex', 'email', 'any'];
          let customTypes = [
            {
              type: 'letters',
              message: '只能输入英文字母',
              pattern: /^[A-Za-z]+$/,
            },
            {
              type: 'capital',
              message: '只能输入大写英文字母',
              pattern: /^[A-Z]+$/,
            },
            {
              type: 'lowercase',
              message: '只能输入小写英文字母',
              pattern: /^[a-z]+$/,
            },
            {
              type: 'numberLetters',
              message: '只能输入数字及英文字母',
              pattern: /^[A-Za-z0-9]+$/,
            },
            {
              type: 'numberLettersUnderline',
              message: '只能输入数字、2英文字母或者下划线',
              pattern: /^\w+$/,
            },
            {
              type: 'characters',
              message: '只能输入汉字',
              pattern: /^[\u4e00-\u9fa5]{0,}$/,
            },
            {
              type: 'ID',
              message: '请输入正确的身份证号',
              pattern: /^\d{15}|\d{18}$/,
            },
            {
              type: 'password',
              message: '以字母开头，长度在6~18之间，只能包含字符、数字和下划线',
              pattern: /^[a-zA-Z]\w{5,17}$/,
            },
            {
              type: 'phoneNumber',
              message: '请输入正确的电话号码',
              pattern: /^\d{15}|\d{18}$/,
            },

          ];
          if(ruleObj[el.field]) {
            if(types.includes(ruleObj[el.field])) {
              rules.push({type: ruleObj[el.field], message: '请输入正确的格式！', trigger: ['blur', 'change']});
            } else {
              let ruleArr = customTypes.filter(ele => ele.type === ruleObj[el.field]);
              ruleArr.forEach(ele => {
                rules.push({pattern: ele.pattern, message: ele.message, trigger: ['blur', 'change']});
              })
            }
          }
        }
        obj.rule = rules;
        return obj;
      })
    };
    // 过滤
    Vue.prototype.setFilter = (e) => {
      let obj = {}, timeStart = null, timeEnd = null, timeField = null, tip = null;
      e.forEach(el => {
        if (el.type === 'checkbox' || el.type === 'multiSelect' || el.type === 'datetimerange' || el.type === 'daterange' || el.type === 'select-cascader' || el.type === 'selectCascader') {
          obj[el['field']] = el.value ? el.value : [];
        } else if (el.field.indexOf('timeStart') !== -1) {
          timeField = el['metaField'] || el.field.replace('timeStart', 'time');
          timeStart = el.value ? el.value : null;
        } else if (el.field.indexOf('timeEnd') !== -1) {
          timeEnd = el.value ? el.value : null;
        } else if (el.type === 'number' && (el.value || el.value === 0)) {
          obj[el['field']] = [el.value];
        } else {
          obj[el['field']] = el.value || el.value === 0 ? [el.value] : undefined;
        }
      })
      if (timeStart || timeEnd) {
        obj[timeField] = [timeStart, timeEnd];
        if (timeStart && timeEnd) {
          let startTime = new Date(timeStart.replace(/-/g, "/"));
          let endTime = new Date(timeEnd.replace(/-/g, "/"));
          if (startTime >= endTime) {
            tip = "开始时间不能大于结束时间，请重新选择时间！"
          }
        }
      }
      return {data: obj, tip};
    }

    // 获取表单 item
    Vue.prototype.getFormItem = (arr, str) => {
      let data = [];
      arr.forEach(el => {
        let obj = JSON.parse(JSON.stringify(el));
        if (obj[str]) {
          obj.hidden = false;
          data.push(obj)
        }
      })
      return data;
    }
    // 获取表单数据
    Vue.prototype.getFormData = (arr) => {
      let obj = {};
      arr.forEach(el => {
        if (el.type === 'number') {
          obj[el.field] = 0;
        } else if (el.type === 'checkbox' || el.type === 'multiSelect' || el.type === 'datetimerange' || el.type === 'daterange' || el.type === 'select-cascader' || el.type === 'selectCascader') {
          obj[el.field] = [];
        } else {
          obj[el.field] = '';
        }
      })
      return obj;
    }

    // 编辑的表单数据
    Vue.prototype.getEditFormData = (arr, list) => {
      let info = {};
      if (list['id']) {
        info['id'] = list['id']
      }
      arr.forEach(d => {
        if (d.field) {
          if (d.type === 'checkbox' || d.type === 'multiSelect' || d.type === 'datetimerange' || d.type === 'daterange' || d.type === 'select-cascader' || d.type === 'selectCascader') {
            if (list[d.field]) {
              try {
                info[d.field] = list[d.field].split(',')
              } catch (err) {
                info[d.field] = list[d.field]
              }
            } else {
              info[d.field] = []
            }
          } else if (d.type === 'number' && !list[d.field]) {
            info[d.field] = 0
          } else if (d.type === 'select' && (list[d.field] || list[d.field] === 0)) {
            let arr = d.option || [];
            arr.forEach(el => {
              if (list[d.field] === el.label) {
                info[d.field] = el.value;
              }
            })
          } else if (!list[d.field] && list[d.field] !== 0) {
            info[d.field] = ''
          } else {
            info[d.field] = list[d.field]
          }
        }
      })
      return info
    }

    // 查看的表单item
    Vue.prototype.getLetterHeader = (cols, str) => {
      let data = cols.map(el => {
        let obj = JSON.parse(JSON.stringify(el));
        if (obj[str]) {
          obj.hidden = false
        }
        obj.type = 'letter';
        return obj
      })
      return data;
    }
    // 获取新增和编辑的字段
    Vue.prototype.getModalDefaultInfo = (cols, str, that) => {
      let info = [];
      cols.forEach(d => {
        if (d[str]) {
          let obj = that.cloneObj(d);
          obj["id"] = d.field;
          obj["label"] = d.header;
          obj.hidden = false;
          (d.type === 'multiSelect' || d.type === 'selectCascader') && (obj["value"] = []);
          obj.required = d.rule && d.rule.required;
          obj.disabled = false;
          info.push(obj);
        }
      });
      return info;
    }

    //使用inputlistview组件的新增、编辑保存时的验证
    Vue.prototype.saveVerification = (items, that) => {
      // console.log("items",items);
      let param = {}, canRequest = true;
      let str = that.checkRequire(items); //检查必填项是否是空项
      if (!that.isEmpty(str)) {
        that.message(that, "warn", str, true);
        canRequest = false;
        return false;
      } else {
        canRequest = true;
      }
      items.forEach(d => {
        if (!Array.isArray(d.value)) { //不是数组
          if (!that.isEmpty(d.value)) {
            if (that.checkReg(d.value, d.label)) {
              param[d.field] = d.value;
            } else {
              str += d.label + "的格式不正确，请更改后再保存<br/>";
              canRequest = false;
            }
          } else {
            param[d.field] = "";
          }
        } else {
          param[d.field] = d.value;
        }
      });
      if (!canRequest) {
        that.message(that, "warn", str, true);
        return false;
      } else {
        return param;
      }
    }
  }
}
